//
//  ICMusicPlayFullScreenVC.m
//  DWTeacher
//
//  Created by icochu on 2022/01/15
//  Copyright © 2022年 wlf. All rights reserved.
//

#import "ICMusicPlayFullScreenVC.h"
#import "UIImage+ImageEffects.h"
#import "ICMusicPlayListVC.h"
#import "XHComMacro.h"
#import "UIButton+Style.h"
#import "UIView+XHAdd.h"
#import "Common.h"
#import "PlayMulitpleView.h"
#import "PlayVoiceSubtitleView.h"
#import "ICMusicPlayManager.h"
#import "PlayMulitpleView.h"
#import <QuickLook/QuickLook.h>
#import "HSVideoPlayViewController.h"
@interface ICMusicPlayFullScreenVC ()<UINavigationControllerDelegate,UIDocumentInteractionControllerDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>
@property(nonatomic, strong) UIView *bottomOprateView;              //底部视图

@property(nonatomic, strong) UIView *middlePlayView;                //中间视图展示
@property(nonatomic, strong) UIProgressView *progressView;          //缓冲进度条
@property(nonatomic, strong) UISlider *sliderView;                  //播放进度条
@property(nonatomic, strong) UIButton *playListBtn;                 //播放列表
@property(nonatomic, strong) UILabel *beginTime;                    //起始时间
@property(nonatomic, strong) UILabel *endTime;                      //结束时间
@property(nonatomic, strong) UIButton *timeBtn;                     //时间倒计时
@property(nonatomic, strong) UIButton *formerBtn;                   //上一首
@property(nonatomic, strong) UIButton *playBtn;                     //播放、暂停
@property(nonatomic, strong) UIButton *nextBtn;                     //下一首
@property(nonatomic, strong) UIButton *cycleBtn;

//前进15S
@property(nonatomic, strong) UIButton *forgeBtn;

//后退15S
@property(nonatomic, strong) UIButton *backAwayBtn;
@property(nonatomic, strong) UIImageView *topBGImageView;           //背景虚图
@property(nonatomic, strong) UIButton *leftBtn;                     //左上角向下按钮

@property(nonatomic, strong) UIImageView *columnBackImageView;      //专栏图片
@property(nonatomic, strong) UILabel *columnTitle;                  //专栏名字
@property(nonatomic, strong) UILabel *articleTitle;                 //文章名字

@property(nonatomic, strong) UIView *timeSelectView;                //时间选择视图
@property(nonatomic, strong) UIView *timeListMaskView;
@property(nonatomic, strong)NSTimer *progressTimer;                  //处理进度
@property (nonatomic, strong) UITextView *contentTextView;
@property (nonatomic,strong)CABasicAnimation *basicAnimation;

@property (nonatomic, strong)PlayVoiceSubtitleView* playsubtitleView;
@property (nonatomic, strong)UIView*       backView;
@property (nonatomic, strong)UIScrollView* scrollView;
@property(nonatomic, strong) UIButton *rightVideoBtn;                //时间选择视图

@property(nonatomic, strong) UILabel *videoTimeLabel;                 //文章名字
@property (nonatomic, strong) UIDocumentInteractionController *documentInteractionControll;
@property(nonatomic,strong)QLPreviewController *previewController;

@end

@implementation ICMusicPlayFullScreenVC {
    NSArray *_btnNameArray;         //底部功能按钮集合
    NSArray *_btnselectArray;       //底部功能选中状态按钮集合
    NSArray *_titleNameArray;       //底部功能按钮标题
    NSMutableArray *_bottomBtns;
    NSArray *_timeListNameArray;            //时间选择视图选择项
    NSMutableArray *_timeButtonArray;
    NSMutableArray *_timeImageViewArray;
    SlidleStatue slideStatue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _bottomBtns = @[].mutableCopy;
    _timeButtonArray = @[].mutableCopy;
    _timeImageViewArray = @[].mutableCopy;
    _btnNameArray = @[@"fullView_ article",@"helpAnswer_com_fablous",@"fullView_ share"];
    _btnselectArray = @[@"fullView_ article",@"helpAnswer_answerDetail_agree_s",@"fullView_ share"];
    _titleNameArray = @[@"文章",@"0",@"分享"];
    _timeListNameArray = @[@"定时关闭",@"不开启",@"播完当前音频后",@"播完2段音频后",@"播完3段音频后",@"10分钟后",@"20分钟后",@"30分钟后",@"取消"];
    
    [self initView];
    [self initTimeView];

}
- (void)setNavigationBarHidden {
    
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        [appearance configureWithOpaqueBackground];
        appearance.backgroundColor = [UIColor clearColor];
        appearance.shadowColor = [UIColor clearColor];
        appearance.backgroundImage = [UIImage new];

        appearance.shadowImage = [UIImage new];
        appearance.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                           NSFontAttributeName: [UIFont boldSystemFontOfSize:18]};
        self.navigationController.navigationBar.standardAppearance = appearance;
        self.navigationController.navigationBar.scrollEdgeAppearance = self.navigationController.navigationBar.standardAppearance;
    }
    
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                NSFontAttributeName: [UIFont boldSystemFontOfSize:18]}];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNavigationBarHidden];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[ICMusicPlayManager sharedManager].currentMusicPlayer pause];
}
- (void)initTopView{
    _topBGImageView = [UIImageView new];
    _topBGImageView.frame = CGRectMake(0, 0, XHScreenWidth, XHScreenHeight);
    [_topBGImageView sd_setImageWithURL:[NSURL URLWithString:self.currentModel.image]];
    _topBGImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:_topBGImageView];
    UIImage *columnImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.currentModel.image]]];
    self.topBGImageView.image = [columnImage applyDarkEffect];
    _leftBtn = [UIButton new];
    _leftBtn.frame = CGRectMake(0, 0, 22, 22);
    [_leftBtn setImage:IMAGE(@"back") forState:UIControlStateNormal];
    [_leftBtn addTarget:self action:@selector(_leftBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftBtn];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftBtn];
    
    self.title = @"每周布道";
    
    _articleTitle = [UILabel new];
    _articleTitle.font = FONT(15);
//    _articleTitle.size = CGSizeMake(100, 24);
//    _articleTitle.left = SCREEN_WIDTH - 100 - 20;
//    _articleTitle.top = 32;
    _articleTitle.frame = CGRectMake(0, 0, 100, 24);
    _articleTitle.textColor = [UIColor whiteColor];
    _articleTitle.textAlignment = NSTextAlignmentRight;
    _articleTitle.numberOfLines = 0;
    _articleTitle.text = _currentModel.teacher_name;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_articleTitle];
    
    UIView* view=[[UIView alloc]initWithFrame:CGRectMake(17,20 + topHeight,wid(5),30)];
    view.backgroundColor=RBG(58,139,231);
    
    [self.view addSubview:view];
    
    UILabel* tipLabel=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(view.frame) + 10, 20 + topHeight,SCREEN_WIDTH-120, 30)];
    tipLabel.textColor=[UIColor whiteColor];
    tipLabel.font=[UIFont boldSystemFontOfSize:FontSize(18)];
    tipLabel.text = [PlayModel sharedModel].currentModel.name;;
    [self.view addSubview:tipLabel];
    
    
    UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-50,topHeight + 20,30,30)];
    [btn setBackgroundImage:[UIImage imageNamed:@"视频"] forState:UIControlStateNormal];
    if (self.currentModel.video_url.length == 0) {
        self.currentModel.video_url = @"https://www.apple.com/105/media/cn/mac/family/2018/46c4b917_abfd_45a3_9b51_4e3054191797/films/bruce/mac-bruce-tpl-cn-2018_1280x720h.mp4";
    }
    btn.hidden = self.currentModel.video_url.length == 0;
    self.rightVideoBtn = btn;
    [self.rightVideoBtn addTarget:self action:@selector(playVideoController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
- (void)initTextView{
    self.backView=[UIView new];
    [self.view addSubview:self.backView];
    
    self.contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH - 40, 150)];
    self.contentTextView.backgroundColor = [UIColor clearColor];
    [self.backView addSubview:self.contentTextView];
    if (self.currentModel.introduce) {
        NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[self.currentModel.introduce dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        self.contentTextView.attributedText = attrStr;
    }
    CGFloat btnWidth=SCREEN_WIDTH/3.0;
    CGFloat height=CGRectGetMaxY(self.contentTextView.frame)+hig(10);
    NSArray* array=self.currentModel.additional;
    NSInteger count = array.count > 6 ? 6: array.count;
    CGFloat titleMaxY = height;
    for(int i=0;i<count;i++){
        NSDictionary *dict = array[i];
        NSInteger x=i%3;
        NSInteger y=i/3;
        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(x*btnWidth,height+y*hig(60),btnWidth,hig(60))];
        [btn setTitle:dict[@"title"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)];
        [self.backView addSubview:btn];
        titleMaxY = height+y*hig(60) + hig(60);
    }
    
    CGFloat tipWidth=[GC_OCTool getWidthForLabel:@"相关: " andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)] andHeight:hig(100)];
    CGFloat tipHeight=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)] andWidth:wid(100)];
    UILabel* lastLabel=[[UILabel alloc]init];
    lastLabel.left = 10;
    lastLabel.top = titleMaxY + 20;
    lastLabel.width = tipWidth;
    lastLabel.height = 20;
    lastLabel.text=@"相关: ";
    lastLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)];
    lastLabel.textColor=[UIColor whiteColor];
    [self.backView addSubview:lastLabel];
    
    NSArray* lableArray = self.currentModel.lable;
    CGFloat lableX = tipWidth + 20;
    for(int i = 0;i < lableArray.count; i++){
        NSDictionary *dict = lableArray[i];
        NSString *labelStr = dict[@"label"];
        CGFloat lableWidth=[GC_OCTool getWidthForLabel:labelStr andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(12)] andHeight:14] + 10;
        lableX = tipWidth + 20 + i * (lableWidth + 10);
        UIButton* btn=[[UIButton alloc]init];
        btn.top = titleMaxY + 20;
        btn.left = lableX;
        btn.width = lableWidth;
        btn.height = 20;
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
        [btn setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateNormal];
        [btn setTitle:labelStr forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(12)];
        [self.backView addSubview:btn];
    }
    
    
    self.scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(tipWidth+wid(25),height,SCREEN_WIDTH-wid(25)-tipWidth,tipHeight)];
    [self.backView addSubview:self.scrollView];
    CGFloat y = CGRectGetMaxY(self.rightVideoBtn.frame) + 20;

    self.backView.frame=CGRectMake(0,y,SCREEN_WIDTH,self.scrollView.y+self.scrollView.height);
}
-(void)upDateView
{
    
    /**刷新文字*/
    [self.playsubtitleView refreshUrl:self.currentModel.srt andFileId:[NSString stringWithFormat:@"%@",self.currentModel.id]];
//    [self refreshPlayUI];
}
//-(void)refreshPlayUI
//{
//    [self.playBtn setBackgroundImage:[UIImage imageNamed:self.isplayer?@"播放":@"暂停"] forState:UIControlStateNormal];
//}
- (void)initView {
    [self initTopView];
    [self initTextView];
    _middlePlayView = [[UIView alloc]initWithFrame:CGRectMake(0, XHScreenHeight - 160 - SafeAreaBottomHeight, XHScreenHeight, 160)];
    [self.view addSubview:_middlePlayView];
    
    _cycleBtn = [UIButton new];
    _cycleBtn.size = CGSizeMake(60, 60);
    _cycleBtn.left = 10;
    _cycleBtn.top = 90;
    NSInteger type=[[NSUserDefaults standardUserDefaults]integerForKey:@"playStyle"];
    NSArray* user=@[@"循环播放",@"单曲播放",@"随机播放"];
    _cycleBtn.titleLabel.font = FONT(12);
    _cycleBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [_cycleBtn setTitleColor:XHAPPTipsColor forState:UIControlStateNormal];
    [_cycleBtn setTitle:user[type] forState:UIControlStateNormal];

    [_cycleBtn setImage:IMAGE(user[type]) forState:UIControlStateNormal];
    [_cycleBtn addTarget:self action:@selector(cycleBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [_cycleBtn layoutButtonWithEdgeInsetsStyle:ICButtonEdgeInsetsStyleTop imageTitleSpace:2];
    [_middlePlayView addSubview:_cycleBtn];
    
    _playListBtn = [UIButton new];
    _playListBtn.size = CGSizeMake(60, 60);
    _playListBtn.right = XHScreenWidth - 10;
    _playListBtn.top = 90;
    [_playListBtn setTitle:@"目录" forState:UIControlStateNormal];
    [_playListBtn setImage:IMAGE(@"目录") forState:UIControlStateNormal];
    _playListBtn.titleLabel.font = FONT(12);
    [_playListBtn setTitleColor:XHAPPTipsColor forState:UIControlStateNormal];
    [_playListBtn layoutButtonWithEdgeInsetsStyle:ICButtonEdgeInsetsStyleTop imageTitleSpace:2];
    [_playListBtn addTarget:self action:@selector(_playListBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [_middlePlayView addSubview:_playListBtn];
    
    _playBtn = [UIButton new];
    _playBtn.size = CGSizeMake(60, 60);
    _playBtn.centerY = _playListBtn.centerY;
    _playBtn.centerX = XHScreenWidth / 2;
    [_playBtn setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal];
    [_playBtn setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forState:UIControlStateSelected];
    [_playBtn setImage:IMAGE(@"暂停") forState:UIControlStateSelected];
    [_playBtn setImage:IMAGE(@"播放") forState:UIControlStateNormal];
    [_playBtn setBackgroundImage:[UIImage imageWithColor:[UIColor blackColor]] forState:UIControlStateDisabled];
    [_playBtn setImage:[UIImage imageNamed:@"LoginLoading"] forState:UIControlStateDisabled];
    [_playBtn addTarget:self action:@selector(_playBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _playBtn.selected = !_isPlaying;
    [_middlePlayView addSubview:_playBtn];
    
    _formerBtn = [UIButton new];
    _formerBtn.size = CGSizeMake(30, 30);
    _formerBtn.right = _playBtn.left - 20;
    _formerBtn.centerY = _playBtn.centerY;
    [_formerBtn setBackgroundImage:IMAGE(@"上一首") forState:UIControlStateNormal];
    [_formerBtn setBackgroundImage:IMAGE(@"fullView_playBtn_left_f") forState:UIControlStateDisabled];
    [_formerBtn addTarget:self action:@selector(_formerBtnAction) forControlEvents:UIControlEventTouchUpInside];
    if (_isFirstMusic) _formerBtn.enabled = NO;
    [_middlePlayView addSubview:_formerBtn];
    
    _nextBtn = [UIButton new];
    _nextBtn.size = CGSizeMake(30, 30);
    _nextBtn.left = _playBtn.right + 20;
    _nextBtn.centerY = _playBtn.centerY;
    [_nextBtn setBackgroundImage:IMAGE(@"下一首") forState:UIControlStateNormal];
    [_nextBtn setBackgroundImage:IMAGE(@"fullView_playBtn_right_f") forState:UIControlStateDisabled];
    [_nextBtn addTarget:self action:@selector(_nextBtnAction) forControlEvents:UIControlEventTouchUpInside];
    if (_isLastMusic) _nextBtn.enabled = NO;
    [_middlePlayView addSubview:_nextBtn];
    
    UIButton* houtuiBtn = [UIButton new];
    houtuiBtn.size = CGSizeMake(60, 60);
    houtuiBtn.left = 10;
    houtuiBtn.top = 20;
    houtuiBtn.tag=999;
    houtuiBtn.titleLabel.font = FONT(12);
    [houtuiBtn addTarget:self action:@selector(seekForwardPlayer:) forControlEvents:UIControlEventTouchUpInside];
    [self setButtonImage:@"后退10秒" ButtonTitle:@"后退10秒" ButtonUI:houtuiBtn];
    [_middlePlayView addSubview:houtuiBtn];
    
    UIButton* qianjinBtn = [UIButton new];
    qianjinBtn.tag=1000;
    qianjinBtn.size = CGSizeMake(60, 60);
    qianjinBtn.right = SCREEN_WIDTH - 10;
    qianjinBtn.top = 20;
    qianjinBtn.titleLabel.font = FONT(12);
    [qianjinBtn addTarget:self action:@selector(seekForwardPlayer:) forControlEvents:UIControlEventTouchUpInside];
    [self setButtonImage:@"前进10秒" ButtonTitle:@"前进10秒" ButtonUI:qianjinBtn];
    [_middlePlayView addSubview:qianjinBtn];
    
    _progressView = [[UIProgressView alloc]init];
    _progressView.left = houtuiBtn.right + 10;
    _progressView.width = SCREEN_WIDTH - 160;
    _progressView.height = 3;
    _progressView.centerY = qianjinBtn.centerY - 10;
    _progressView.layer.masksToBounds = YES;
    _progressView.layer.cornerRadius = 1.5;
    _progressView.trackTintColor= UIColor.whiteColor;          //设置进度条颜色
    _progressView.progressTintColor= UIColor.lightTextColor;      //缓冲进度条上进度的颜色
    _progressView.progress = _buffingProgress / self.currentModel.audioLength;
    [_middlePlayView addSubview:_progressView];
    
    _sliderView = [[UISlider alloc]init];
    _sliderView.left = houtuiBtn.right + 7;
    _sliderView.width = SCREEN_WIDTH - 160;
    _sliderView.height = 30;
    _sliderView.centerY = qianjinBtn.centerY - 10;
    _sliderView.layer.masksToBounds = YES;
    _sliderView.layer.cornerRadius = 1.5;
    _sliderView.minimumValue = 0;
    _sliderView.maximumValue = self.currentModel.audioLength;
    _sliderView.value = self.currentProgress;
    _sliderView.continuous = YES;
//    _sliderView.minimumTrackTintColor = XHAPPMainColor;
//    _sliderView.maximumTrackTintColor = [UIColor clearColor];
    [_sliderView addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];

    [_sliderView addTarget:self action:@selector(sliderTouchUpInSide:) forControlEvents:UIControlEventTouchUpInside];
    [_sliderView addTarget:self action:@selector(sliderTouchUpInSide:) forControlEvents:UIControlEventTouchUpOutside];
    
    [_sliderView addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    
//    [_sliderView setThumbImage:IMAGE(@"fullView_progress") forState:UIControlStateNormal];
    [_middlePlayView addSubview:_sliderView];
    
    _videoTimeLabel = [UILabel new];
    _videoTimeLabel.size = CGSizeMake(100, 20);
    _videoTimeLabel.centerX = SCREEN_WIDTH / 2;
    _videoTimeLabel.bottom = _sliderView.top - 10;
    _videoTimeLabel.text = @"00:00/00:00";
    _videoTimeLabel.font = FONT(16);
    _videoTimeLabel.textColor = UIColor.whiteColor;
    _videoTimeLabel.hidden = YES;
    [_middlePlayView addSubview:_videoTimeLabel];
    
    _beginTime = [UILabel new];
    _beginTime.left = _progressView.left;
    _beginTime.top = _progressView.bottom + 10;
    _beginTime.size = CGSizeMake(80, 14);
    _beginTime.text = @"00:00";
    _beginTime.font = FONT(12);
    _beginTime.textColor = UIColor.whiteColor;
    [_middlePlayView addSubview:_beginTime];
    [Common updataTimerLableWithLable:_beginTime Second:_currentProgress];
    
    _endTime = [UILabel new];
    _endTime.left = _progressView.right - 80;
    _endTime.top = _progressView.bottom + 10;
    _endTime.size = CGSizeMake(80, 14);
    _endTime.textAlignment = NSTextAlignmentRight;
    _endTime.text = @"00:00";
    _endTime.font = FONT(12);
    _endTime.textColor = UIColor.whiteColor;
    [_middlePlayView addSubview:_endTime];
    [Common updataTimerLableWithLable:_endTime Second:_currentModel.audioLength];
    [self initProssage];
}
- (void)initProssage{
    
    _bottomOprateView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(_middlePlayView.frame) - 60, XHScreenWidth, 55)];
    
    [self.view addSubview:_bottomOprateView];
    NSArray* iconImage=@[@"字幕关闭",@"定时器关闭",@"倍速1.0",@"目录"];
    for (NSInteger i = 0; i < iconImage.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.imageView.contentMode = UIViewContentModeScaleAspectFit;
        CGFloat jx=(SCREEN_WIDTH-20*2-50*4)/3.0;
        button.frame = CGRectMake(20+i*(jx+50),0,50,50);
        button.tag = 100 + i;
        [button setTitleColor:XHAPPTipsColor forState:UIControlStateNormal];
        button.titleLabel.font = FONT(12);
        [button setImage:[UIImage imageNamed:iconImage[i]] forState:UIControlStateNormal];
        [button setTitle:iconImage[i] forState:UIControlStateNormal];
        [self setButtonImage:iconImage[i] ButtonTitle:iconImage[i] ButtonUI:button];
        button.tag=400+i;
        if (i==1) {
            self.timeBtn = button;
            NSString *timeS = _clockTime > 0 ? [Common updataTimerLableWithSecond:_clockTime] : @"定时关闭";
            [_timeBtn setTitle:timeS forState:UIControlStateNormal];
            _timeBtn.titleLabel.font = FONT(12);
            _timeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
            [_timeBtn addTarget:self action:@selector(timeBtnAction) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        [_bottomOprateView addSubview:button];
        [_bottomBtns addObject:button];
    }
    
}
- (void)initTimeView {
    _oldSelectTimeIndex = _currentSelectTimeIndex;
    _timeListMaskView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, XHScreenWidth, XHScreenHeight)];
    _timeListMaskView.alpha = 0.5;
    _timeListMaskView.backgroundColor = XHUIColorFromRGB(0x000000);
    _timeListMaskView.hidden = YES;
    UITapGestureRecognizer *timeListMaskViewTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(timeListMaskViewTapAction)];
    [_timeListMaskView addGestureRecognizer:timeListMaskViewTap];
    [self.view addSubview:_timeListMaskView];
    
    _timeSelectView = [[UIView alloc]initWithFrame:CGRectMake(0, XHScreenHeight, XHScreenWidth, 445 + SafeAreaBottomHeight)];
    _timeSelectView.backgroundColor = XHAPPSeparateColor;
    for (NSInteger i = 0; i < _timeListNameArray.count; i++) {
        UIButton *btn = [UIButton new];
        [btn setTitle:_timeListNameArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:XHAPPTitleColor forState:UIControlStateNormal];
        [btn setTitleColor:XHAPPMainColor forState:UIControlStateSelected];
        btn.tag = 100 + i;
        btn.layer.borderWidth = 0.5;
        btn.layer.borderColor = XHAPPBGColor.CGColor;
        btn.layer.masksToBounds = YES;
        btn.backgroundColor = [UIColor whiteColor];
        [btn addTarget:self action:@selector(timeBtnSelectAction:) forControlEvents:UIControlEventTouchUpInside];
        [_timeSelectView addSubview:btn];
        [_timeButtonArray addObject:btn];
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = IMAGE(@"icon_check_h");
        imageView.hidden = (i == _currentSelectTimeIndex) ? NO : YES;
        [btn addSubview:imageView];
        [_timeImageViewArray addObject:imageView];
        
        if (i == 0) {
            btn.frame = CGRectMake(0, 0, XHScreenWidth, 44);
            [btn setTitleColor:XHAPPSubheadColor forState:UIControlStateNormal];
            btn.titleLabel.font = FONT(14);
            imageView.frame = CGRectMake(XHScreenWidth - 15 - 22, 11 , 22, 22);
        }else {
            if (i == _timeListNameArray.count - 1) {
                btn.frame = CGRectMake(0, 445 - 50 , XHScreenWidth, 50 + SafeAreaBottomHeight);
                btn.selected = YES;
            }else {
                btn.frame = CGRectMake(0, 44 + (i - 1) * 49, XHScreenWidth, 49);
                imageView.frame = CGRectMake(XHScreenWidth - 15 - 22, 13.5 , 22, 22);
                btn.selected = (i == _currentSelectTimeIndex) ? YES : NO;
            }
        }
    }
    [self.view addSubview:_timeSelectView];
}

#pragma mark - set
- (void)setCurrentModel:(ICMusicPlayModel *)currentModel {
    if (currentModel == nil) return;
    _currentModel  = currentModel;
    //中间图
//    _columnBackImageView.image = [UIImage imageWithContentsOfFile:_currentModel.image];
    _columnTitle.text = currentModel.teacher_name;
    _articleTitle.text = currentModel.teacher_name;
    
    //进度条
    self.totleTime = self.currentModel.audioLength;
    self.sliderView.maximumValue = self.currentModel.audioLength;//音乐总共时长
    [Common updataTimerLableWithLable:_endTime Second:currentModel.audioLength];
    
    //上一首，下一首，更新定时显示
    if(self.selectTimeZone != SelectTimeZoneTwo)[self computationTimeDisplayTimeLableWithSelectZone:self.selectTimeZone NewModel:currentModel];
}

- (void)setCurrentProgress:(NSTimeInterval)currentProgress {
    _currentProgress = currentProgress;
    _sliderView.value  = currentProgress;
    [Common updataTimerLableWithLable:_beginTime Second:currentProgress];
}
- (void)setBuffingProgress:(NSTimeInterval)buffingProgress {
    _buffingProgress = buffingProgress;
    _progressView.progress =  buffingProgress / self.currentModel.audioLength;;
}

- (void)setTotleTime:(NSTimeInterval)totleTime {
    _totleTime = totleTime;
    [Common updataTimerLableWithLable:_endTime Second:totleTime];
}
- (void)setIsLastMusic:(BOOL)isLastMusic {
    _isLastMusic = isLastMusic;
    _nextBtn.enabled = !isLastMusic;
}
- (void)setIsFirstMusic:(BOOL)isFirstMusic {
    _isFirstMusic = isFirstMusic;
    _formerBtn.enabled = !isFirstMusic;
}
- (void)setIsPlaying:(BOOL )isPlaying {
    _isPlaying = isPlaying;
    _playBtn.selected = !isPlaying;
}
- (void)setClockTime:(NSInteger)clockTime {
    _clockTime = clockTime;
    //当选择10分钟以上定时，由外部管理定时不需要重新计算
    if (self.currentSelectTimeIndex > 4) return;
    NSString *timeS = _clockTime > 0 ? [Common updataTimerLableWithSecond:_clockTime] : @"定时关闭";
    [self setButtonImage:@"" ButtonTitle:timeS ButtonUI:_timeBtn];
}

#pragma mark - prive
- (void)playVideoController{
    HSVideoPlayViewController *vc = [[HSVideoPlayViewController alloc] init];
    vc.playUrl = self.currentModel.video_url;
    vc.currentModel = self.currentModel;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)setButtonImage:(NSString *)imageName
           ButtonTitle:(NSString *)title
              ButtonUI:(UIButton *)button{
    if (title.length > 0) {
        [button setTitle:title forState:UIControlStateNormal];
    }
    if (imageName.length > 0) {
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    [button layoutButtonWithEdgeInsetsStyle:ICButtonEdgeInsetsStyleTop imageTitleSpace:2];
}
-(void)btnAction:(UIButton*)sender
{
    if(sender.tag==400)
    {
        if(self.currentModel)
        {
            self.backView.alpha=!self.backView.alpha;
            [sender setImage:[UIImage imageNamed:self.backView.alpha?@"字幕关闭":@"字幕开启"] forState:UIControlStateNormal];
            self.playsubtitleView.alpha=!self.backView.alpha;
        }else
        {
            [GC_OCTool startTishil:@"正在请求数据..."];
        }
    }else if(sender.tag==401)/**定时器*/{
        PlayMulitpleView *view = [[PlayMulitpleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        view.mulitBlock = ^(NSString * _Nonnull mulit) {
            
        };
        
        UIView *superView = UIApplication.sharedApplication.keyWindow.rootViewController.view;
        if (!superView) {
            superView = [UIApplication sharedApplication].keyWindow;
        }
        [view showIn:superView];
    }else if(sender.tag==402)/**倍速*/{
        
        PlayMulitpleView *view = [[PlayMulitpleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        view.dataSource = @[@"0.5",@"1.0",@"1.25",@"1.5",@"2.0",@"2.5",@"3.0"];
        view.mulitBlock = ^(NSString * _Nonnull mulit) {
            [ICMusicPlayManager sharedManager].currentMusicPlayer.rate = mulit.floatValue;
            [sender setImage:[UIImage imageNamed:[NSString stringWithFormat:@"倍速%@", mulit]] forState:UIControlStateNormal];
        };
        
        UIView *superView = UIApplication.sharedApplication.keyWindow.rootViewController.view;
        if (!superView) {
            superView = [UIApplication sharedApplication].keyWindow;
        }
        [view showIn:self.view];
    }else{
        
        QLPreviewController *qlpreVc = [[QLPreviewController alloc] init];
        qlpreVc.delegate = self;
        qlpreVc.dataSource = self;
        [self presentViewController:qlpreVc animated:YES completion:nil];
    }
}
- (void)readDocWithDucument{
//    NSString * ducumentLocation = [[NSBundle mainBundle]pathForResource:@"⽤户模块接⼝" ofType:@"docx"];
    NSURL *url = [NSURL fileURLWithPath:self.currentModel.file];
    _documentInteractionControll= [UIDocumentInteractionController interactionControllerWithURL:url];
    _documentInteractionControll.delegate = self;
//    [_documentInteractionController presentPreviewAnimated:YES];
    [_documentInteractionControll presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
}

/**快进*/
-(void)seekForwardPlayer:(UIButton*)sender
{
    CGFloat value=0.0;
    if(sender.tag==1000)
    {
       value=self.currentProgress+10;
    }else
    {
        value=self.currentProgress-10;
    }
    if(value<0)
    {
        value=0.0;
    }else if(value>self.currentModel.audioLength)
    {
        value=self.currentModel.audioLength;
    }
    self.sliderView.value = value;
    [self sliderTouchUpInSide:self.sliderView];
}
- (void)cycleBtnAction{
    [[PlayModel sharedModel] changePlayStyle];
    NSArray* user = @[@"循环播放",@"单曲播放",@"随机播放"];
    [_cycleBtn setTitle:user[[PlayModel sharedModel].playStyle] forState:UIControlStateNormal];

    [_cycleBtn setImage:IMAGE(user[[PlayModel sharedModel].playStyle]) forState:UIControlStateNormal];
    
    [_cycleBtn layoutButtonWithEdgeInsetsStyle:ICButtonEdgeInsetsStyleTop imageTitleSpace:2];
}

- (void)_leftBtnAction {
   
    if (self.progressTimer != nil) {
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
    //传出数据
    if (self.closeBtnAction) self.closeBtnAction(_currentModel,_clockTime, _currentSelectTimeIndex,_isPlaying);
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - delegate

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}

- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    NSURL *url = [NSURL URLWithString:self.currentModel.file];
    return url;
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}
-(UIView  *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return self.view;
}
-(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    return self.view.bounds;
}

#pragma mark - 底部三个按钮
- (CABasicAnimation *)basicAnimation {
    if (_basicAnimation == nil) {
        self.basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        //旋转一圈时长
        self.basicAnimation.duration = 30;
        //开始动画的起始位置
        self.basicAnimation.fromValue = [NSNumber numberWithInt:0];
        //M_PI是180度
        self.basicAnimation.toValue = [NSNumber numberWithInt:M_PI*2];
        //动画重复次数
        [self.basicAnimation setRepeatCount:NSIntegerMax];
        //播放完毕之后是否逆向回到原来位置
        [self.basicAnimation setAutoreverses:NO];
        //是否叠加（追加）动画效果
        [self.basicAnimation setCumulative:YES];
        //停止动画，速度设置为0
        self.playBtn.layer.speed = 1;
        //    self.ImageView.layer.speed = 0;
        [self.playBtn.layer addAnimation:self.basicAnimation forKey:@"basicAnimation"];
        
    }
    return _basicAnimation;
}
- (void)beginImageViewAnimate {
    self.playBtn.enabled = NO;
    [self.playBtn.layer removeAllAnimations];//移除动画
    self.basicAnimation = nil;
    [self basicAnimation];//开始动画
    self.isRunningAnimate = YES;
}

- (void)continueImageViewAnimate {
    self.playBtn.enabled = NO;
    //得到view当前动画时间偏移量
    CFTimeInterval stopTime = [self.playBtn.layer timeOffset];
    //初始化开始时间
    self.playBtn.layer.beginTime = 0;
    //初始化时间偏移量
    self.playBtn.layer.timeOffset = 0;
    //设置动画速度
    self.playBtn.layer.speed = 1;
    //计算时间差
    CFTimeInterval tempTime = [self.playBtn.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
    //重新设置动画开始时间
    self.playBtn.layer.beginTime = tempTime;
}

- (void)stopImageViewAnimate {
    self.playBtn.selected = YES;
    self.isRunningAnimate = NO;
    _playBtn.selected = YES;
    CFTimeInterval stopTime = [self.playBtn.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //停止动画，速度设置为0
    self.playBtn.layer.speed = 0;
    //设置时间偏移量
    self.playBtn.layer.timeOffset = stopTime;
}


#pragma mark - 中间播放控制视图按钮
- (void)_playListBtnAction {
    //弹出列表
    ICMusicPlayListVC *plistVC = [ICMusicPlayListVC new];
    plistVC.allListModelArray = self.musicArray;
    plistVC.currentModel = self.currentModel;
    plistVC.isPlaying = self.isPlaying;
    @weakify(self)
    plistVC.readPlayMusic = ^(NSInteger currentSelectTimeListIndex, ICMusicPlayModel *model) {
        @strongify(self)
        if(self.readPlayMusic)self.readPlayMusic(currentSelectTimeListIndex, model);
    };
    [self.navigationController pushViewController:plistVC animated:YES];
}
- (void)timeBtnAction {
    //弹出时间列表
    _timeListMaskView.hidden = NO;
    for (NSInteger i = 0; i < _timeImageViewArray.count; i++) {
        UIImageView *imageView = _timeImageViewArray[i];
        imageView.hidden = (i == _currentSelectTimeIndex) ? NO : YES;
        UIButton *button = _timeButtonArray[i];
        if (i == 0) {
            button.selected = NO;
        }else {
            if (i == _timeListNameArray.count - 1) {
                button.selected = YES;
            }else {
                button.selected = (i == _currentSelectTimeIndex) ? YES : NO;
            }
        }
    }
    _oldSelectTimeIndex = _currentSelectTimeIndex;
    [UIView animateWithDuration:0.3 animations:^{
        self->_timeSelectView.top = XHScreenHeight - 445 - SafeAreaBottomHeight;
    }];
}
- (void)_playBtnAction:(UIButton *)button {
    //播放、暂停
    button.selected = !button.selected;
    _isPlaying = !button.selected;
    if (self.playBtnAction) self.playBtnAction(button.selected);
}

- (void)_formerBtnAction {
    //上一曲,先处理定时
    self.currentProgress = 0;
    if(self.formerBtnAction) self.formerBtnAction(self.currentSelectTimeIndex);
}

- (void)_nextBtnAction {
    //下一曲,先处理定时
    self.currentProgress = 0;
    if (self.nextBtnAction) self.nextBtnAction(self.currentSelectTimeIndex);
}

-(void)sliderValueChanged:(UISlider *)slider {
    [Common updataTimerLableWithLable:_beginTime Second:slider.value];
    self.videoTimeLabel.text = [NSString stringWithFormat:@"%@/%@", _beginTime.text, _endTime.text];
}

- (void)sliderTouchDown:(UISlider *)slider{
    self.videoTimeLabel.hidden = NO;
    [[ICMusicPlayManager sharedManager].currentMusicPlayer pause];
}
- (void)sliderTouchUpInSide:(UISlider *)slider {
    self.videoTimeLabel.hidden = YES;
    [[ICMusicPlayManager sharedManager].currentMusicPlayer play];
    //滑动进度条暂停
    if (slider.value > self.currentProgress) {
        slideStatue = MoveForward;
    }else {
        slideStatue = MoveBack;
    }
    self.currentProgress = slider.value;
    if (self.seekProgress) self.seekProgress(slider.value);
    //设置完进度后更新时间
    if(self.selectTimeZone != SelectTimeZoneTwo) [self computationTimeDisplayTimeLableWithSelectZone:self.selectTimeZone NewModel:self.currentModel];
}
#pragma mark - 选择定时时间
- (void)timeBtnSelectAction:(UIButton *)button {
    NSInteger index = button.tag - 100;
    if (index == _timeListNameArray.count - 1) {
        [self timeListMaskViewTapAction];
    }else {
        [self selectClockTimeWithIndex:button.tag - 100];
    }
}
//时间选中后的实现
- (void)timeListMaskViewTapAction {
    _timeListMaskView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self->_timeSelectView.top = XHScreenHeight;
    }completion:^(BOOL finished) {
        //开始计时
        if(self->_oldSelectTimeIndex == self->_currentSelectTimeIndex)return;
        [self computationTimeDisplayTimeLableWithSelectZone:self.selectTimeZone NewModel:self.currentModel];
    }];
}

- (void)updataTimeShowWithCurrentTime:(NSInteger)time {
    if (time == 0) {
        [_timeBtn setTitle:@"定时关闭" forState:UIControlStateNormal];
    }else {
        NSString *timertitle = [Common updataTimerLableWithSecond:time];
        [_timeBtn setTitle:timertitle forState:UIControlStateNormal];
    }
    [_timeBtn layoutButtonWithEdgeInsetsStyle:ICButtonEdgeInsetsStyleTop imageTitleSpace:2];
}
#pragma mark - private
- (void)computationTimeDisplayTimeLableWithSelectZone:(SelectTimeZone)zone NewModel:(ICMusicPlayModel *)model{
    //计算时间
    self.clockTime = (zone == SelectTimeZoneNone) ? 0 : [self totleTimeClockWithIndex:_currentSelectTimeIndex CurrentModel:model ModelArray:self.musicArray];
 if(self.currentClockTime) self.currentClockTime(self.clockTime,zone,self.currentSelectTimeIndex);
}

- (void)selectClockTimeWithIndex:(NSInteger)index{
    if (index == 1) {
        self.selectTimeZone = SelectTimeZoneNone;
    }else if (1 < index && index < 5) {
        self.selectTimeZone = SelectTimeZoneOne;
    }else if (4 < index && index < 8) {
        self.selectTimeZone = SelectTimeZoneTwo;
    }
    if (index < 1 || index > 7 || (_currentSelectTimeIndex == index)) return;
    //其他
    for (NSInteger i = 1; i < _timeListNameArray.count; i++) {
        UIButton *btn = _timeButtonArray[i];
        UIImageView *imageView = _timeImageViewArray[i];
        btn.selected = i == index ? YES : NO;
        imageView.hidden = i == index ? NO : YES;
    }
    //记录选项
    _currentSelectTimeIndex = index;
}

- (void)updateTimeShow {
    NSString *timertitle = [Common updataTimerLableWithSecond:_clockTime];
    [_timeBtn setTitle:timertitle forState:UIControlStateNormal];
    [_timeBtn layoutButtonWithEdgeInsetsStyle:ICButtonEdgeInsetsStyleTop imageTitleSpace:2];
}

//计算定时
- (NSInteger)totleTimeClockWithIndex:(NSInteger)index CurrentModel:(ICMusicPlayModel *)model ModelArray:(NSArray *)musicArray{
    if (index < 1 || index > 7) return 0;
   __block NSInteger clockSum = 0;
    if (index > 1 && index < 5) {
        //正常播放完成的去除
        NSInteger newIndex = self.overPlayNum > 0 ? (index - self.overPlayNum) : index;
        for (NSInteger i = 0; i < newIndex - 1; i++) {
            CurriculumModel *playModel = musicArray[i];

            [[ICMusicPlayManager sharedManager].oprationPlay getIndexModelWith:model.rownum + i Complete:^(ICMusicPlayModel * _Nonnull model) {
                
                clockSum += model.audioLength;
                //如果是正在播放的歌曲，减去当前播放歌曲的进度
                if([self.currentModel.audio_url isEqualToString: model.audio_url]){
                    clockSum -= self.currentProgress;
                };
            }];
          
        }
    }else if(index == 1){
        clockSum = 0;
    }else {
        clockSum = 600 * (index - 4);
    }
    return clockSum;
}
#pragma mark - getters and setters
-(PlayVoiceSubtitleView*)playsubtitleView
{
    if(!_playsubtitleView)
    {
        _playsubtitleView=[[PlayVoiceSubtitleView alloc]initWithFrame:self.backView.frame];
        _playsubtitleView.alpha=0;
        [self.view addSubview:_playsubtitleView];
    }
    return _playsubtitleView;
}
@end
